package com.gigmissions.client.ui.presenters;

import java.util.List;

import com.gigmissions.client.dto.Artist;
import com.gigmissions.client.dto.Venue;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.geocode.Geocoder;
import com.google.gwt.maps.client.geocode.LocationCallback;
import com.google.gwt.maps.client.geocode.Placemark;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class MapPresenter {
	
	private MapWidget map;
	
	@Inject
	public MapPresenter(final MapWidget map){
		this.map = map;
		
	}
	
	public void present(List<Artist> artists){
		
		//geo code the address and add lats & longs to map
		
		for(Artist a:artists){
			
			Venue venue = a.getEvents().get(0).getVenue();
			
			String address = venue.getGeocodeableAddress();
			
			if(venue.getLat()==null||venue.getLat().length()==0){
				//use lat/longs if we have it otherwise geocode AND store it for the future.
				final Geocoder geocoder = new Geocoder(); 
				geocoder.getLocations(address +" ,AU", new LocationCallback(){

					@Override
					public void onFailure(int statusCode) {
						
					  
					}
				
					@Override
					public void onSuccess(JsArray<Placemark> locations) {
						
						//always take first location
						Marker marker = new Marker(locations.get(0).getPoint());
						map.addOverlay(marker);
						
						
					}
					
				});
			
			}else{
				LatLng latlng = LatLng.newInstance(Double.parseDouble(venue.getLat()), Double.parseDouble(venue.getLng()));
				Marker marker = new Marker(latlng);
				map.addOverlay(marker);
			}
		}
		
		
		
		
		
	}
	
}
